package jnpf.base.service.impl;


import com.baomidou.mybatisplus.annotation.DbType;
import jnpf.base.entity.DbLinkEntity;
import jnpf.base.service.DbSyncService;
import jnpf.base.service.DblinkService;
import jnpf.base.util.DbSyncUtil;
import jnpf.util.JdbcUtil;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.ResultSet;

/**
 * 数据同步
 *
 * @author 南通渡课开发平台组
 * @version V3.1.0
 * @copyright 南通渡课信息技术有限公司
 * @date 2019年9月27日 上午9:18
 */
@Slf4j
@Service
public class DbSyncServiceImpl implements DbSyncService {

    @Autowired
    private DblinkService dblinkService;

    @Override
    public String importTableData(String dbConnectionFrom, String dbConnectionTo, String table){
        DbLinkEntity linkFrom = dblinkService.getInfo(dbConnectionFrom);
        DbLinkEntity linkTo = dblinkService.getInfo(dbConnectionTo);
        String s = linkFrom.getHost() + linkFrom.getPort() + linkFrom.getServiceName();
        String s1 = linkTo.getHost() + linkTo.getPort() + linkTo.getServiceName();
        if (s.equals(s1)){
            return "同一连接下不能同步数据";
        }
        try {
            @Cleanup Connection connectionStringFrom = JdbcUtil.getConn(linkFrom.getDbType(), linkFrom.getUserName(), linkFrom.getPassword(), linkFrom.getHost(), linkFrom.getPort(), linkFrom.getServiceName());
            @Cleanup Connection connectionStringTo = JdbcUtil.getConn(linkTo.getDbType(), linkTo.getUserName(), linkTo.getPassword(), linkTo.getHost(), linkTo.getPort(), linkTo.getServiceName());
            if(connectionStringFrom==null){
                return "数据库"+linkFrom.getFullName()+"连接失败";
            }
            if(connectionStringTo==null){
                return "数据库"+linkTo.getFullName()+"连接失败";
            }
            String toSql = "SELECT count(*) FROM " + table;
            ResultSet result =JdbcUtil.query(connectionStringTo, toSql);
            int rowCount=0;
            if (result.next())
            {
                rowCount = result.getInt(1);
            }
            if(rowCount>0){
                return "同步失败,目标表存在数据";
            }
            String fromSql = "SELECT * FROM " + table;
            ResultSet resultFrom = JdbcUtil.query(connectionStringFrom, fromSql);
            if(linkTo.getDbType().toLowerCase().equals(DbType.ORACLE.getDb())){
                DbSyncUtil.oracleTableSync(connectionStringTo,resultFrom,table);
            }else{
                DbSyncUtil.tableSync(connectionStringTo,resultFrom,table);
            }
            return "ok";
        } catch (Exception e) {
            return(e.getMessage());
        }
    }
}
